#设置专题状态
import datetime
import pymysql
import requests
import json

from concurrent.futures import ThreadPoolExecutor
from dbutils.pooled_db import PooledDB


# 测试库
def getBetaConnection():
    pool = PooledDB(pymysql, 1, host='172.20.150.110', user='test_movie', passwd='test_movie154104',
                db='cc_media_source', port=4308)  # 1为连接池里的最少连接数
    conn = pool.connection()
    cur = conn.cursor()
    return conn, cur

# 正式库
def getProdConnection():
    pool = PooledDB(pymysql, 1, host='193.112.206.244', user='developer_read', passwd='developer_read#coocaa',
                    db='cc_media_source', port=3306)  # 1为连接池里的最少连接数
    conn = pool.connection()
    cur = conn.cursor()
    return conn, cur


#设置专题状态
def copyTrack():
    #conn, cur = getBetaConnection()
    conn, cur = getProdConnection()
    try:
        # 获取总记录数
        #total_count_sql = "SELECT COUNT(*) FROM (select md5,count(1) from cc_ancient_poetry t where 1=1 group by t.md5 having count(1)>1 ) tt"
        #cur.execute(total_count_sql)
        #total_count = cur.fetchone()[0]
        total_count = 28000
        batch_size = 100
        offset = 0

        while offset < total_count:
            # 使用LIMIT和OFFSET进行分页查询
            select_sql = f"""
                select t.span_id,t.gen_type,t.categorys,t.params from cc_smart_strategy_track t
                 where t.create_time > '2025-09-24' and t.create_time <= '2025-09-26 16:00:00' and t.gen_status = 1
                and (select tt.status from cc_smart_topic tt where tt.tid = t.tid) = 1
                LIMIT {batch_size} OFFSET {offset}
                """
            cur.execute(select_sql)
            results = cur.fetchall()

            if not results:
                # 如果没有更多数据，则退出循环
                break
            track_list = []
            ids = []
            for result in results:
                span_id = result[0]
                gen_type = result[1]
                categorys = result[2]
                params = result[3]
                new_span_id = span_id[:-1] + "a"
                track_dict = {
                    "sid":"xe2inxlcp9p1c",
                    "stype":"tag_by_random",
                    "media_type":"video",
                    "spanId":new_span_id,
                    "genType":gen_type,
                    "categorys":categorys,
                    "params":params,
                }
                track_list.append(track_dict)
                ids.append(id)
            print(f"第{offset}序号的策略进行复制")
            create_api(track_list)

            # 更新offset以进行下一次查询
            offset += batch_size

    finally:
        # 确保无论如何都关闭数据库连接
        cur.close()
        conn.close()

def create_api(update_data):
    #url = "http://localhost:8080/api/ccSmartStrategy/saveStrategyTrack/invoke"
    url = "http://106.55.8.90:7001/api/ccSmartStrategy/saveStrategyTrack/invoke"
    headers = {'Content-Type': 'application/json'}
    response = requests.request("POST", url, headers=headers, data=json.dumps(update_data))
    if response.status_code == 200:
        print(f":数据保存成功")
    else:
        print(f"数据保存失败，状态码：{response.status_code}")


if __name__ == '__main__':
    copyTrack()